<template>
  <div class="erOrInput">
    <div class="scan phoneLogin" v-if="erOrInput == 2">
      <!-- <svg-icon icon-class="yzm_icon" @click="switchFn" /> -->
      <p class="cutBtn " @click="switchFn(3)">App扫码登录<svg-icon icon-class="sm_icon" /></p>
      <p class="cutBtn scanBtn" @click="switchFn(1)">
        验证码登录<svg-icon icon-class="yzm_icon" />
      </p>

      <!-- 密码登录 -->
      <template v-if="!isReset">
        <h3>密码登录</h3>
        <p></p>
        <el-input
          v-model="dataForm.mobile"
          placeholder="请输入手机号"
        ></el-input>
        <el-input
          v-model="dataForm.password"
          placeholder="请输入密码"
          show-password
        ></el-input>
        <el-button round @click="getLogin">登录</el-button>

        <div class="agreement-box">
          <el-checkbox v-model="dataForm.checked"></el-checkbox>
          同意问三师
          <span @click="getUserAreement" class="agreement">《用户协议》</span>、
          <span @click="getPrivacyAreement" class="agreement"
            >《隐私协议》</span
          >
          <div class="forgetPw">
            <p @click="clickIsReset">忘记密码？</p>
            <p @click="regAccount">注册账号</p>
          </div>
        </div>
      </template>

      <!-- 重置密码/注册账号 -->
      <template v-else>
        <h3 v-if="isResOrReg">注册账号</h3>
        <h3 v-else>重置密码</h3>
        <p></p>
        <el-input
          v-model="dataForm.mobile"
          placeholder="请输入手机号"
        ></el-input>
        <el-input
          v-model="dataForm.code"
          placeholder="请输入验证码"
          @blur="verifyCodeFn"
        >
          <span
            slot="suffix"
            @click="obtainVerifyCode"
            :style="{
              color: verifyContent.disabled ? 'grey' : '#f87a23',
              cursor: verifyContent.disabled ? 'unset' : 'pointer'
            }"
          >
            {{ verifyContent.disabled ? verifyContent.text : "获取验证码" }}
          </span>
        </el-input>
        <el-input
          v-model="dataForm.password"
          placeholder="请输入8~18位字符(需包含数字、字母)"
          show-password
          :disabled="!isPass"
        ></el-input>
        <el-button round @click="setPassword">确定</el-button>

        <div class="agreement-box">
          <el-checkbox v-model="dataForm.checked"></el-checkbox>
          同意问三师
          <span @click="getUserAreement" class="agreement">《用户协议》</span>、
          <span @click="getPrivacyAreement" class="agreement"
            >《隐私协议》</span
          >
        </div>
      </template>
    </div>

    <!-- 验证码登录 -->
    <div class="phoneLogin" v-if="erOrInput == 1">
      <!-- <svg-icon icon-class="ewm_icon" @click="switchFn" /> -->
      <p class="cutBtn" @click="switchFn(3)">App扫码登录<svg-icon icon-class="sm_icon" /></p>
      <p class="cutBtn scanBtn" @click="switchFn(2)">
        密码登录<svg-icon icon-class="mm_icon" />
      </p>
      <h3>验证码登录</h3>
      <p>未注册的手机号将自动注册并登录</p>
      <el-input v-model="dataForm.mobile" placeholder="请输入手机号"></el-input>
      <el-input v-model="dataForm.code" placeholder="请输入验证码">
        <span
          slot="suffix"
          @click="obtainVerifyCode"
          :style="{
            color: verifyContent.disabled ? 'grey' : '#f87a23',
            cursor: verifyContent.disabled ? 'unset' : 'pointer'
          }"
        >
          {{ verifyContent.disabled ? verifyContent.text : "获取验证码" }}
        </span>
        <!-- <el-button slot="suffix" @click="obtainVerifyCode"
          ></el-button
        > -->
      </el-input>
      <el-button round @click="handlerLogin">登录/注册</el-button>
      <div class="agreement-box">
        <el-checkbox v-model="dataForm.checked"></el-checkbox>
        同意问三师
        <span @click="getUserAreement" class="agreement">《用户协议》</span>、
        <span @click="getPrivacyAreement" class="agreement">《隐私协议》</span>
      </div>
    </div>
    <div class="phoneLogin" v-if="erOrInput == 3">
      <!-- <svg-icon icon-class="ewm_icon" @click="switchFn" /> -->
      <p class="cutBtn" @click="switchFn(1)">
        验证码登录<svg-icon icon-class="yzm_icon" />
      </p>
      <p class="cutBtn scanBtn" @click="switchFn(2)">
        密码登录<svg-icon icon-class="mm_icon" />
      </p>
      <template>
        <h3>手机扫码 安全登录</h3>
        <p>请使用问三师 App 扫码登录</p>
        <!-- <img :src="~@/assets/images/er.png" alt="" /> -->
        <div class="codeImg-box">
          <img :src="codeImg" alt="" />
          <div class="refresh" v-if="qrCodeType == 2">
            <div>
              <p>二维码已失效</p>
              <button @click="getQrCode()">立即刷新</button>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import { getDocRichTextApi } from "@/BMViews/api/doc/richText.js";
import {
  getOrderListApi,
  getVerificationCodeApi,
  getmobileRegisterApi,
  getLoginApi,
  getUserProfileRetrievePwdApi,
  getUserRegisterApi,
  createLoginQrcodeApi, //创建扫码登录
  qrcodeLoginApi,       //查询状态
} from "@/BMViews/api/login.js";
import { getRouteTypeListFn } from "@/router/index.js";
import { getBudgetServiceListApi } from "@/BMViews/api/budget/budgetService.js";
import qrcodeParser from 'qrcode-parser'; //二维码解析
import { debounce } from "@/wss/utils/wss.js";
export default {
  props: {
    erOrInput: {
      type: [String,Number],
      default: 1
    },
    redirect: {
      type: undefined,
      default: undefined
    }
  },
  data() {
    return {
      token: "",
      // 表单初始化数据
      dataForm: {
        channeId: "",
        checked: false,
        // type: "USERNAME",
        mobile: "",
        code: "",
        password: "",
        smsCode: ""
      },

      isReset: false, // 当前是否是重置密码和注册账号
      isResOrReg: false, //false重置密码 true注册账号
      isPass: false, //当前验证码是否通过

      // 获取验证码按钮
      verifyContent: {
        disabled: false,
        text: "获取验证码",
        time: 60
      },

      areementData: {} ,//当前协议信息
      codeImg:'',
      qrTime:'',
      qrCodeType: 0,
      codeText:'',
    };
  },
  mounted() {
    // 隐私协议是typeId=5的时候跳过去 路由传参
    if (this.$route.query.typeId == "5") {
      this.getPrivacyAreement();
    }
    if(this.erOrInput == 3){
      console.log('2222222222222222222');
      this.getQrCode()
    }
  },
  // 销毁事件
  beforeDestroy() {
    clearInterval(this.qrTime);
  },
  methods: {
    // 获取用户协议
    async getUserAreement() {
      this.$emit("update:isagreement", true);
      await this.getDocRichTextFn("6");
      this.$bus.$emit("busAreement", this.areementData);
    },

    // 获取隐私协议
    async getPrivacyAreement() {
      this.$emit("update:isagreement", true);
      await this.getDocRichTextFn("5");
      this.$bus.$emit("busAreement", this.areementData);
    },

    async getDocRichTextFn(typeId) {
      let { code, data } = await getDocRichTextApi({ typeId });
      if (code != 200) return;
      this.areementData = data.rows[0];
    },
    switchFn(erOrInput) {
      this.isReset = false; // 当前是否是重置密码
      this.isPass = false; //当前验证码是否通过
      this.$emit("update:erOrInput", erOrInput);
      if(erOrInput == 3){
        this.getQrCode()
      }else{
        clearInterval(this.qrTime);
      }
    },
    //获取二维码
    async getQrCode(){
      let { code, msg } = await createLoginQrcodeApi();
      if(code == 200){
        this.codeImg = msg;
        this.qrCodeType = 1;
        if(!msg) return;
        qrcodeParser(msg).then(res=>{
          console.log(res);
          this.codeText = res;
          this.qrTime = setInterval(() => {
            this.getQrCodeType()
          }, 5000);
        }).catch(err => {
          console.log(err);
        });

      }
    },
    //获取登录状态
    async getQrCodeType(){
      qrcodeLoginApi({
        code: this.codeText,
      }).then(res=>{
        if(res.code == 200){
          if(res?.data?.token){
            //登录成功
            clearInterval(this.qrTime);
            let token = res.data.token;
            this.$store.dispatch("codeLogin", token).then(async () => {
              // 在sessionStorage有存储登录之前的链接就跳转
              let fullPath = sessionStorage.getItem("fullPath");
              sessionStorage.removeItem("fullPath");
              if (fullPath) {
                console.log(fullPath, "进到了对应的页面");
                this.$router.push({ path: fullPath }).catch(err => {
                  console.log(err);
                });
              } else {
                console.log("去首页");
                this.$router.push({
                  path: "/Bm-tool/budget"
                });
              }
              // 获取用户信息
              await this.$store.dispatch("GetInfo").then(() => {
                this.$WebSocket.initialize(); //登录之后全局调用webscoket
                this.$WebSocket2.initialize(); //登录之后全局调用webscoket
                // this.$TencentCall.initialize(); //登录im
              })
              //获取阿米巴预算服务
              this.$store.dispatch("getBudget").then(() => {});
              // 获取圈员列表
              this.$store.dispatch("getCircleStaffList").then(() => {});
              //获取阿米巴预算角色
              this.$store.dispatch("getBudgetRole").then(() => {});
            });
          }
        }
      }).catch(err=>{
        console.log('请求错误',err);
        // clearInterval(this.qrTime);
      })

    },
    // 登录的回调
    async handlerLogin() {
      if (!this.dataForm.checked || !this.dataForm.code) {
        this.$message({
          type: "warning",
          message: this.dataForm.checked ? "请输入验证码" : "请勾选协议"
        });
        return;
      }
      let { code, token } = await getmobileRegisterApi(this.dataForm);
      if (code != 200) return;
      this.dataForm.code = "";
      // 登录
      this.$store.dispatch("codeLogin", token).then(async () => {
        // 在sessionStorage有存储登录之前的链接就跳转
        let fullPath = sessionStorage.getItem("fullPath");
        sessionStorage.removeItem("fullPath");
        if (fullPath) {
          console.log(fullPath, "进到了对应的页面");
          this.$router.push({ path: fullPath }).catch(err => {
            console.log(err);
          });
        } else {
          console.log("去首页");
          this.$router.push({
            path: "/Bm-tool/budget"
          });
        }
        // 获取用户信息
        await this.$store.dispatch("GetInfo").then(() => {
          this.$WebSocket.initialize(); //登录之后全局调用webscoket
          this.$WebSocket2.initialize(); //登录之后全局调用webscoket
          // this.$TencentCall.initialize(); //登录im
        })
        //获取阿米巴预算服务
        this.$store.dispatch("getBudget").then(() => {});
        // 获取圈员列表
        this.$store.dispatch("getCircleStaffList").then(() => {});
        //获取阿米巴预算角色
        this.$store.dispatch("getBudgetRole").then(() => {});
      });
    },
    // 发送验证码
    async obtainVerifyCode() {
      var self = this;
      if (self.verifyContent.disabled) {
        return;
      }
      if (self.validePhone()) {
        // 防抖
        debounce(async () => {
          // 发送短信接口请求
          let { code } = await getOrderListApi(this.dataForm.mobile);
          if (code != 200) return;
          self.countDown(); //倒计时
          this.$message({
            type: "success",
            message: "已发送"
          });
        }, 300)();
      }
    },
    // 倒计时方法
    countDown() {
      var time = 60;
      this.verifyContent.disabled = true;
      this.verifyContent.text = `重新获取(${time}s)`;
      var timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.verifyContent.disabled = false;
          this.verifyContent.text = "获取验证码";
        } else {
          this.verifyContent.disabled = true;
          this.verifyContent.text = `重新获取(${time}s)`;
          time--;
          // this.verifyContent.time--;
        }
      }, 1000);
    },
    // 验证手机号
    validePhone() {
      if (["", null, undefined].includes(this.dataForm.mobile)) {
        this.$message({
          type: "warning",
          message: "请输入手机号"
        });
        return false;
      } else if (!/^1[3456789]\d{9}$/.test(this.dataForm.mobile)) {
        this.$message({
          type: "warning",
          message: "请输入正确的手机号码"
        });
        return false;
      } else {
        return true;
      }
    },
    // 注册方法
    dataFormSubmit() {
      var self = this;
      if (self.validePhone()) {
        if (!["", null, undefined].includes(self.dataForm.code)) {
          // 發送請求
          console.log("可以发送接口");
        } else {
          Toast("请输入验证码");
        }
      }
    },

    // 密码登录
    passWdLogin() {},

    // 密码登录的接口
    async getLogin() {
      if (!this.dataForm.checked) {
        this.$message({
          type: "warning",
          message: "请勾选协议"
        });
        return;
      }

      let userInfo = {
        username: this.dataForm.mobile,
        password: this.dataForm.password
      };
      let { code, token } = await getLoginApi(userInfo);
      if (code != 200) return;
      this.dataForm.code = "";
      // 登录
      this.$store.dispatch("codeLogin", token).then(async () => {
        // 在sessionStorage有存储登录之前的链接就跳转
        let fullPath = sessionStorage.getItem("fullPath");
        sessionStorage.removeItem("fullPath");
        if (fullPath) {
          this.$router.push({ path: fullPath }).catch(err => {
            console.log(err);
          });
        } else {
          this.$router.push({
            path: "/Bm-tool/budget"
          });
        }
        // 获取用户信息
        await this.$store.dispatch("GetInfo").then(() => {
          this.$WebSocket.initialize(); //登录之后全局调用webscoket
          this.$WebSocket2.initialize(); //登录之后全局调用webscoket
          // this.$TencentCall.initialize(); //登录im
        })
        //获取阿米巴预算服务
        this.$store.dispatch("getBudget").then(() => {});
        // 获取圈员列表
        this.$store.dispatch("getCircleStaffList").then(() => {});
        //获取阿米巴预算角色
        this.$store.dispatch("getBudgetRole").then(() => {});
      });
    },

    // 点击忘记密码
    clickIsReset() {
      this.isReset = true; //当前是重置密码
      this.isResOrReg = false; //false重置密码 true注册账号
    },

    // 验证验证码
    async verifyCodeFn() {
      if (this.dataForm.code == "" || this.dataForm.code.length != 4) return;
      let { code, smsCode } = await getVerificationCodeApi({
        code: this.dataForm.code,
        mobile: this.dataForm.mobile,
        type: 1
      });
      if (code != 200) return;
      this.dataForm.smsCode = smsCode;
      this.isPass = true;
    },

    // 点击重置密码 /注册账号
    async setPassword() {
      if (!this.dataForm.checked) {
        this.$message({ type: "warning", message: "请勾选协议" });
        return;
      }

      let reg = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,18}$/;
      if (!reg.test(this.dataForm.password)) {
        this.$message({
          type: "warning",
          message: "请输入8~18位字符(需包含数字、字母)"
        });
      } else {
        // this.isResOrReg //false重置密码 true注册账号
        if (this.isResOrReg) {
          await this.getUserRegister(); //注册账号接口
          this.getLogin(); //登录的接口
        } else {
          await this.getUserProfileRetrievePwd(); //重置密码接口
          this.getLogin(); //登录的接口
        }
      }
    },

    // 重置密码/修改密码
    async getUserProfileRetrievePwd() {
      let data = {
        phonenumber: this.dataForm.mobile,
        newPassword: this.dataForm.password,
        code: this.dataForm.smsCode
      };
      let result = await getUserProfileRetrievePwdApi(data);
      if (result.code == 200) {
        this.$message({
          type: "success",
          message: result.msg
        });
      }
    },

    // 点击注册账号按钮的回调
    regAccount() {
      this.isReset = true; //当前是注册账号
      this.isResOrReg = true; //false重置密码 true注册账号
    },

    // 注册账号的接口
    async getUserRegister() {
      let data = {
        phonenumber: this.dataForm.mobile,
        newPassword: this.dataForm.password
      };
      let result = await getUserRegisterApi(data);
      if (result.code == 200) {
        this.$message({
          type: "success",
          message: result.msg
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
/* 高度 */
::v-deep .label-box-content,
::v-deep .label-box-content .el-row,
::v-deep .label-box-content .el-col,
::v-deep .label-box-content .el-col > div,
::v-deep .label-box-content .el-card,
::v-deep .label-box-content .el-card__body {
  height: 100%;
}
::v-deep .el-card__body {
  position: relative;
}
::v-deep .el-card__body > div {
  height: 100%;
  overflow-y: auto;
}
::v-deep .label-box-content .el-card__body > div::-webkit-scrollbar {
  width: 0px;
}
::v-deep .login_main .top {
  display: none;
}
ul,
h3,
p {
  list-style: none;
  margin: 0;
  padding: 0;
}

/* 登录 */
.erOrInput {
  display: flex;
  justify-content: center;
  padding: 80px 0;
  position: relative;
}
.scan {
  text-align: center;
}
.phoneLogin {
  text-align: center;
  width: 100%;
}
// /* 登录 */
.erOrInput .cutBtn {
  position: absolute;
  top: 0px;
  right: 0;
  font-size: 12px;
  font-weight: 400;
  color: #686975;
  margin: 0;
  padding: 8px 20px;
  background: #f1f3ff;
  border-radius: 16px 0px 0px 16px;
  border: 1px solid #e5e6e9;
  cursor: pointer;
}
.erOrInput .cutBtn > svg {
  margin-left: 7px;
}
.erOrInput .cutBtn.scanBtn {
  top: 50px;
}

.erOrInput h3 {
  font-size: 30px;
  font-weight: bold;
}
.erOrInput p {
  font-size: 14px;
  color: #666;
  margin-top: 20px;
  margin-bottom: 50px;
}
.erOrInput img {
  width: 250px;
}
.phoneLogin p {
  margin-bottom: 30px;
}
.phoneLogin .forgetPw {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}
.phoneLogin .forgetPw > p {
  color: #f87a23;
  font-size: 12px;
  cursor: pointer;
  margin: 0 5px;
  margin-bottom: 0;
}
.phoneLogin .el-input {
  width: 60%;
  margin-bottom: 20px;
}
::v-deep .phoneLogin .el-input input {
  border: 0;
  border-bottom: 1px solid #ebebeb;
  height: 50px;
  line-height: 50px;
}
.phoneLogin .el-input .el-button {
  border: 0;
  padding: 16px 0px;
  color: #f87a23;
  background-color: transparent;
}
.phoneLogin .el-input .el-button:hover {
  background-color: transparent;
}
.phoneLogin > .el-button {
  display: block;
  margin: 0 auto;
  width: 60%;
  border-color: #f87a23;
  background-color: #f87a23;
  color: #fff;
  font-weight: bold;
  font-size: 16px;
}

/* 协议 */
.phoneLogin .el-checkbox {
  margin-top: 30px;
}
::v-deep .phoneLogin .el-checkbox__label {
  color: #666;
}
::v-deep .phoneLogin .el-checkbox__label > span {
  color: #f87a23;
}
::v-deep .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: #f87a23;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #f87a23;
  border-color: #f87a23;
}
.agreement-box {
  font-size: 12px;
}
.agreement {
  color: #f87a23;
  cursor: pointer;
}

@media (max-width: 1710px) {
  div.erOrInput {
    padding: 50px 0;
    padding-bottom: 25px;
  }
}

@media (max-width: 1180px) {
  div.erOrInput {
    padding: 50px 0;
  }
  .erOrInput h3 {
    font-size: 26px;
  }
  .phoneLogin p {
    margin-bottom: 15px;
  }
  ::v-deep .phoneLogin .el-input.el-input--medium input {
    height: 40px;
    line-height: 40px;
  }
}
@media (max-width: 1120px) {
  div.erOrInput {
    padding: 50px 0;
    padding-bottom: 25px;
  }
}
.codeImg-box{
  width:250px;
  height:250px;
  position: relative;
  margin:0 auto;
}
.codeImg-box .refresh{
  width:100%;
  height:100%;
  background:rgba(0,0,0,0.7);
  position: absolute;
  top:0;
  left:0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.codeImg-box .refresh p{
  color:#fff;
}
.codeImg-box .refresh button{
  background: #f87a23;
  color:#fff;
  border:0;
  border-radius: 100px;
  padding:4px 10px
}
</style>
